<?php

/**
 +-----------------------------------------------------
 * PublicModel
 +-----------------------------------------------------
 * @author	liuricheng 
 * @time	2014-03-13
 * @type	[add]
 * 
 */
import("ORG.Util.Function");
import("@.Org.Utils");


class GoodsModel extends Model{

	// 变量
	private  $table		=	"ybr_goods";
	
	// 获取商品属性
	public function build_Attr_Html($cat_id,$goods_id){
		$sql	=	"
					SELECT a.attr_id, a.attr_name, a.attr_input_type, a.attr_type, a.attr_values, v.attr_value, v.attr_price 
					FROM `shop`.`ybr_attribute` AS a 
					LEFT JOIN `shop`.`ybr_goods_attr` AS v ON v.attr_id = a.attr_id AND v.goods_id = '{$goods_id}' 
					WHERE a.cat_id = {$cat_id} OR a.cat_id = 0 
					ORDER BY a.sort_order, a.attr_type, a.attr_id, v.attr_price, v.goods_attr_id
					";
		$attr	=	$this->query($sql);
		$html 	= 	'<table width="100%" id="attrTable">';
	    $spec 	= 	0;	
	    foreach ($attr AS $key => $val)
	    {
	        $html .= "<tr><td class='label'>";
	        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
	        {
	            $html .= ($spec != $val['attr_id']) ?
	                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
	                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
	            $spec = $val['attr_id'];
	        }
	
	        $html .= "$val[attr_name]</td><td><input type='hidden' name='attr_id_list[]' value='$val[attr_id]' />";
	
	        if ($val['attr_input_type'] == 0)
	        {
	            $html .= '<input name="attr_value_list[]" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
	        }
	        elseif ($val['attr_input_type'] == 2)
	        {
	            $html .= '<textarea name="attr_value_list[]" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
	        }
	        else
	        {
	            $html .= '<select name="attr_value_list[]">';
	            $html .= '<option value="">' .'请选择...'. '</option>';
	
	            $attr_values = explode("\n", $val['attr_values']);
	
	            foreach ($attr_values AS $opt)
	            {
	                $opt    = trim(htmlspecialchars($opt));
	
	                $html   .= ($val['attr_value'] != $opt) ?
	                    '<option value="' . $opt . '">' . $opt . '</option>' :
	                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
	            }
	            $html .= '</select> ';
	        }
	
	        $html .= ($val['attr_type'] == 1 || $val['attr_type'] == 2) ?
	            $GLOBALS['_LANG']['spec_price'].' <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
	            ' <input type="hidden" name="attr_price_list[]" value="0" />';	
	        $html .= '</td></tr>';
	    }	
	    $html .= '</table>';	
	    return $html;
	}
	
	// 获取商品列表
	public function getGoodsList($filter){
		$sql	=	"SELECT goods_id, goods_name, shop_price FROM `shop`.`ybr_goods` AS g";
		$where	=	$this->get_where_sql($filter); // 帅选条件
		return $this->query($sql . $where);
	}
	
	/**
	 * 生成过滤条件：用于 get_goodslist 和 get_goods_list
	 * @param   object  $filter
	 * @return  string
	 */
	function get_where_sql($filter){
	    $time = date('Y-m-d');	    
	    $where  = isset($filter['is_delete']) && $filter['is_delete'] == '1' ?' WHERE is_delete = 1 ' : ' WHERE is_delete = 0 ';
	    $where .= isset($filter['cat_id']) && $filter['cat_id'] > 0 ? ' AND ' . $this->get_children($filter['cat_id']) : '';
	    $where .= isset($filter['brand_id']) && $filter['brand_id'] > 0 ? " AND brand_id = '" . $filter['brand_id'] . "'" : '';
	    $where .= isset($filter->exclude) ? ' AND goods_id NOT ' . $this->db_create_in($filter->exclude) : '';
	    return $where;
	}
	
	
	public function get_children($cat_id){
		return 'g.cat_id ' . $this->db_create_in(array_unique(array_merge(array($cat_id), array_keys($this->cat_list($cat_id, 0, false)))));		
	}
	

	/**
	 * 创建像这样的查询: "IN('a','b')";
	 *
	 * @access   public
	 * @param    mix      $item_list      列表数组或字符串
	 * @param    string   $field_name     字段名称
	 *
	 * @return   void
	 */
	function db_create_in($item_list, $field_name = ''){
	    if (empty($item_list)){
	        return $field_name . " IN ('') ";
	    }
	    else{
	        if (!is_array($item_list)){
	            $item_list = explode(',', $item_list);
	        }
	        $item_list = array_unique($item_list);
	        $item_list_tmp = '';
	        foreach ($item_list AS $item){
	            if ($item !== ''){
	                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
	            }
	        }
	        if (empty($item_list_tmp)){
	            return $field_name . " IN ('') ";
	        }
	        else{
	            return $field_name . ' IN (' . $item_list_tmp . ') ';
	        }
	    }
	}
	
	public function cat_list($cat_id = 0){
		static $res = NULL;

	    if ($res === NULL){
	        	
            $sql = 	" SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children "
            		." FROM ybr_category  AS c "
               		." LEFT JOIN  ybr_category  AS s ON s.parent_id=c.cat_id "
                	." GROUP BY c.cat_id "
                	." ORDER BY c.parent_id, c.sort_order ASC ";
            //$res = $GLOBALS['db']->getAll($sql); 
            // 最好是可以缓存起来，不用每次都到数据库取           
            $res	=	$this->query($sql);             

            $sql = "SELECT cat_id, COUNT(*) AS goods_num " .
                    " FROM " . 'ybr_goods' .
                    " WHERE is_delete = 0 AND is_on_sale = 1 " .
                    " GROUP BY cat_id";
            //$res2 = $GLOBALS['db']->getAll($sql);
            $res2	=	$this->query($sql);			
            
            $sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " .
                    " FROM " . 'ybr_goods_cat' . " AS gc , " . 'ybr_goods' . " AS g " .
                    " WHERE g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " .
                    " GROUP BY gc.cat_id";
            //$res3 = $GLOBALS['db']->getAll($sql);
            $res3	=	$this->query($sql);
            //echo $sql;	    
            
            $newres = array();
            foreach($res2 as $k=>$v){
                $newres[$v['cat_id']] = $v['goods_num'];
                foreach($res3 as $ks=>$vs){
                    if($v['cat_id'] == $vs['cat_id']){
                    $newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
                    }
                }
            }
            foreach($res as $k=>$v){
                $res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
            }            
	    }
	    if (empty($res) == true){
	        return $re_type ? '' : array();
	    }
	    $options = $this->cat_options($cat_id, $res); // 获得指定分类下的子分类的数组
	    return $options;
	}
	
	/**
	 * 过滤和排序所有分类，返回一个带有缩进级别的数组
	 *
	 * @access  private
	 * @param   int     $cat_id     上级分类ID
	 * @param   array   $arr        含有所有分类的数组
	 * @param   int     $level      级别
	 * @return  void
	 */
	public function cat_options($spec_cat_id, $arr){
	    static $cat_options = array();
	    // 递归算法:最简单使用
	  	// $cat_options	=	$this->catsort($arr,0,0);
	  	$options		=	$this->catsort($arr,0,0);
	  	$cat_options[0] = 	$options;
	    // while循环:ecshop的算法
//	    if (!isset($cat_options[0])){
//	        $level = $last_cat_id = 0;
//	        $options = $cat_id_array = $level_array = array();
//            while (!empty($arr))
//            {
//                foreach ($arr AS $key => $value){
//                    $cat_id = $value['cat_id'];
//                    if ($level == 0 && $last_cat_id == 0){
//                        if ($value['parent_id'] > 0)
//                        {
//                            break;
//                        }
//
//                        $options[$cat_id]          = $value;
//                        $options[$cat_id]['level'] = $level;
//                        $options[$cat_id]['id']    = $cat_id;
//                        $options[$cat_id]['name']  = $value['cat_name'];
//                        unset($arr[$key]);
//
//                        if ($value['has_children'] == 0)
//                        {
//                            continue;
//                        }
//                        $last_cat_id  = $cat_id;
//                        $cat_id_array = array($cat_id);
//                        $level_array[$last_cat_id] = ++$level;
//                        continue;
//                    }
//
//                    if ($value['parent_id'] == $last_cat_id)
//                    {
//                        $options[$cat_id]          = $value;
//                        $options[$cat_id]['level'] = $level;
//                        $options[$cat_id]['id']    = $cat_id;
//                        $options[$cat_id]['name']  = $value['cat_name'];
//                        unset($arr[$key]);
//
//                        if ($value['has_children'] > 0)
//                        {
//                            if (end($cat_id_array) != $last_cat_id)
//                            {
//                                $cat_id_array[] = $last_cat_id;
//                            }
//                            $last_cat_id    = $cat_id;
//                            $cat_id_array[] = $cat_id;
//                            $level_array[$last_cat_id] = ++$level;
//                        }
//                    }
//                    elseif ($value['parent_id'] > $last_cat_id)
//                    {
//                        break;
//                    }
//                }
//
//                $count = count($cat_id_array);
//                if ($count > 1)
//                {
//                    $last_cat_id = array_pop($cat_id_array);
//                }
//                elseif ($count == 1)
//                {
//                    if ($last_cat_id != end($cat_id_array))
//                    {
//                        $last_cat_id = end($cat_id_array);
//                    }
//                    else
//                    {
//                        $level = 0;
//                        $last_cat_id = 0;
//                        $cat_id_array = array();
//                        continue;
//                    }
//                }
//
//                if ($last_cat_id && isset($level_array[$last_cat_id]))
//                {
//                    $level = $level_array[$last_cat_id];
//                }
//                else
//                {
//                    $level = 0;
//                }
//            }
//	        $cat_options[0] = $options;
//	    }
//	    else
//	    {
//	        $options = $cat_options[0];
//	    }
	    
	    // cat_id 为0,直接返回数组,否则找到指定cat_id下的
	    if (!$spec_cat_id){
	        return $options;
	    }
	    else{
	        if (empty($options[$spec_cat_id])){
	            return array();
	        }
	
	        $spec_cat_id_level = $options[$spec_cat_id]['level'];
	
	        foreach ($options AS $key => $value){
	            if ($key != $spec_cat_id){
	                unset($options[$key]);
	            }
	            else{
	                break;
	            }
	        }
	
	        $spec_cat_id_array = array();
	        foreach ($options AS $key => $value){
	            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) || ($spec_cat_id_level > $value['level'])){
	                break;
	            }
	            else{
	                $spec_cat_id_array[$key] = $value;
	            }
	        }
	        $cat_options[$spec_cat_id] = $spec_cat_id_array;
	        return $spec_cat_id_array;
	    }
	}
	
	
	/**
	 * Category Sort
	 * @abstract $list 中键值,以数组中的cat_id作为键值
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['parent_id'] == $parent_id){
				$v['level']  		= 	$lev;
				$v['id']  			= 	$v['cat_id'];
				$v['name']  		= 	$v['cat_name'];
				//$list[]]    = $v;
				$list[$v['cat_id']] = 	$v;
				$this->catsort($arr,$v['cat_id'],$lev +1);
			}
		}
		return $list;
	}
	
	// 获取配件下的所有商品
	public function get_group_goods($goods_id){
	    $sql 	= 	"SELECT gg.goods_id, CONCAT(g.goods_name, ' -- [', gg.goods_price, ']') AS goods_name " .
            		"FROM " . 'ybr_group_goods' . " AS gg, " .
                	'ybr_goods' . " AS g " .
            		"WHERE gg.parent_id = '$goods_id' " .
            		"AND gg.goods_id = g.goods_id ";                
	    if ($goods_id == 0){
	        $sql .= " AND gg.admin_id = '1'";
	    }
   		return $this->query($sql);
	}
	
	// 获取文章
	public function getArticleList(){
	    $where = " WHERE cat_id > 0 ";
	    if (!empty($filters['title'])){
	        $keyword  = trim($filters['title']);
	        $where   .=  " AND title LIKE '%" . Utils::mysql_like_quote($keyword) . "%' ";
	    }
	
	    $sql        = 'SELECT article_id, title FROM ' .' ybr_article'. $where.
	                  'ORDER BY article_id DESC LIMIT 50';
	    return $this->query($sql);
	}
	
	// 获取aritcle列表
	public function get_goods_articles(){
		$sql = 	"SELECT g.article_id, a.title " . "FROM " . 'ybr_goods_article' . " AS g, " . 'ybr_article' . " AS a " .
            	"WHERE g.goods_id = '$goods_id' " .
	            "AND g.article_id = a.article_id ";
	    if ($goods_id == 0){
	        $sql .= " AND g.admin_id = '1'";
	    }
	    return $this->query($sql);
	}
	
	/**
	 * 获得指定商品相关的商品
	 *
	 * @access  public
	 * @param   integer $goods_id
	 * @return  array
	 */
	public function get_linked_goods($goods_id){
	    $sql = 	"SELECT lg.link_goods_id AS goods_id, g.goods_name, lg.is_double " . "FROM " . 'ybr_link_goods' . " AS lg, " . 'ybr_goods' . " AS g " .
	            "WHERE lg.goods_id = '$goods_id' " .
	            "AND lg.link_goods_id = g.goods_id ";
	    if ($goods_id == 0){
	        $sql .= " AND lg.admin_id = '1'";
	    }
	    $row				=	$this->query($sql);
	    
	    foreach ($row AS $key => $val){
	        $linked_type 	= 	$val['is_double'] == 0 ? '单向' : '双向';	
	        $row[$key]['goods_name'] = $val['goods_name'] . " -- [$linked_type]";
	        unset($row[$key]['is_double']);
	    }
	    return $row;
	}
	
	
	
    /**
     * 判断表中某字段是否重复，若重复则中止程序，并给出错误信息
     *
     * @access  public
     * @param   string  $col    字段名
     * @param   string  $name   字段值
     * @param   integer $id
     *
     * @return void
     */
    function is_only($col, $name, $id = 0, $where=''){
        $sql = 'SELECT COUNT(*) count FROM ' .$this->table. " WHERE $col = '$name'";
        $sql .= empty($id) ? '' : ' AND ' . $this->id . " <> '$id'";
        $sql .= empty($where) ? '' : ' AND ' .$where;
        $result	=	$this->query($sql);
       	return ($result[0]['count'] == 0);
    }
		
	/**
	 * 为某商品生成唯一的货号
	 * @param   int     $goods_id   商品编号
	 * @return  string  唯一的货号
	 */
	public static function  generate_goods_sn($goods_id){
	    $goods_sn 	=	"YBR_" . str_repeat('0', 6 - strlen($goods_id)) . $goods_id;
	
	    $sql 		= 	"SELECT goods_sn FROM " . 'ybr_goods' .
	            		" WHERE goods_sn LIKE '" . Utils::mysql_like_quote($goods_sn) . "%' AND goods_id <> '$goods_id' " .
	            		" ORDER BY LENGTH(goods_sn) DESC";
	    $sn_list 	=	M()->query($sql);	    
	    //t($sql);	    
	    if (in_array($goods_sn, $sn_list[0])){
	        $max 	= 	pow(10, strlen($sn_list[0]) - strlen($goods_sn) + 1) - 1;
	        $new_sn = $goods_sn . mt_rand(0, $max);
	        while (in_array($new_sn, $sn_list)){
	            $new_sn = $goods_sn . mt_rand(0, $max);
	        }
	        $goods_sn = $new_sn;
	    }	
	    return $goods_sn;
	}
	
	/**
	 * 保存某商品的会员价格
	 * @param   int     $goods_id   商品编号
	 * @param   array   $rank_list  等级列表
	 * @param   array   $price_list 价格列表
	 * @return  void
	 */
	public static function handle_member_price($goods_id, $rank_list, $price_list){
	 	/* 循环处理每个会员等级 */
	    foreach ($rank_list AS $key => $rank){
	        /* 会员等级对应的价格 */
	        $price 	= 	$price_list[$key];	
	        // 插入或更新记录
	        $sql 	= 	"SELECT COUNT(*) count FROM " . 'ybr_member_price' . " WHERE goods_id = '$goods_id' AND user_rank = '$rank'";
	        
	        $result	=	M()->query($sql);
	        if ($result[0]['count'] > 0){
	            /* 如果会员价格是小于0则删除原来价格，不是则更新为新的价格 */
	            if ($price < 0){
	                $sql 	= 	"DELETE FROM " . 'ybr_member_price' . " WHERE goods_id = '$goods_id' AND user_rank = '$rank' LIMIT 1";
	            }
	            else{
	                $sql 	= 	"UPDATE " . 'ybr_member_price' . " SET user_price = '$price' " ."WHERE goods_id = '$goods_id' " . "AND user_rank = '$rank' LIMIT 1";
	            }
	        }
	        else{
	            if ($price == -1){
	                $sql = '';
	            }
	            else{
	                $sql 	= 	"INSERT INTO " . 'yr_member_price' . " (goods_id, user_rank, user_price) " . "VALUES ('$goods_id', '$rank', '$price')";
	            }
	        }
	
	        if ($sql){
	            M()->query($sql);
	        }
	    }
	}
	
	/**
	 * 保存某商品的优惠价格
	 * @param   int     $goods_id    商品编号
	 * @param   array   $number_list 优惠数量列表
	 * @param   array   $price_list  价格列表
	 * @return  void
	 */
	public static function handle_volume_price($goods_id, $number_list, $price_list){
	    $sql 	= 	"DELETE FROM " . 'ybr_volume_price' . " WHERE price_type = '1' AND goods_id = '$goods_id'";
	   	M()->query($sql);
	   	
	    /* 循环处理每个优惠价格 */
	    foreach ($price_list AS $key => $price){
	        /* 价格对应的数量上下限 */
	        $volume_number 	= 	$number_list[$key];	
	        if (!empty($price)){
	            $sql 		= 	"INSERT INTO " . 'ybr_volume_price' . " (price_type, goods_id, volume_number, volume_price) " . "VALUES ('1', '$goods_id', '$volume_number', '$price')";
	            M()->query($sql);
	        }
	    }
	}
	
	/**
	 * 保存某商品的扩展分类
	 * @param   int     $goods_id   商品编号
	 * @param   array   $cat_list   分类编号数组
	 * @return  void
	 */
	public static function handle_other_cat($goods_id, $cat_list){		
	    /* 查询现有的扩展分类 */
	    $sql 			= 	"SELECT cat_id FROM " . 'ybr_goods_cat' . " WHERE goods_id = '$goods_id'";
	    $exist_list 	= 	M()->query($sql);
	
	    /* 删除不再有的分类 */
	    $delete_list 	= 	array_diff($exist_list, $cat_list);
	    if ($delete_list){
	        $sql 		= 	"DELETE FROM " . 'ybr_goods_cat' . " WHERE goods_id = '$goods_id' " . "AND cat_id " . Utils::db_create_in($delete_list);
	        M()->query($sql);
	    } 
	
	    /* 添加新加的分类 */
	    $add_list 		= 	array_diff($cat_list, $exist_list, array(0));
	    foreach ($add_list AS $cat_id){
	        // 插入记录
	        $sql 		= 	"INSERT INTO " . 'ybr_goods_cat' . " (goods_id, cat_id) " . "VALUES ('$goods_id', '$cat_id')";
	        M()->query($sql);
	    }
	}
	
	/**
	 * 保存某商品的关联商品
	 * @param   int     $goods_id
	 * @return  void
	 */
	public static function handle_link_goods($goods_id){
	    $sql 	= 	"UPDATE " . 'ybr_link_goods' . " SET " . " goods_id = '$goods_id' " . " WHERE goods_id = '0'" . " AND admin_id = '1'";
	    //$GLOBALS['db']->query($sql);
	    M()->query($sql);
	
	    $sql 	= 	"UPDATE " . 'ybr_link_goods' . " SET " . " link_goods_id = '$goods_id' " . " WHERE link_goods_id = '0'" 
	    			." AND admin_id = '1'";
	    M()->query($sql);
	}
	
	/**
	 * 保存某商品的配件
	 * @param   int     $goods_id
	 * @return  void
	 */
	function handle_group_goods($goods_id){
	    $sql = "UPDATE " . 'ybr_group_goods' . " SET " . " parent_id = '$goods_id' " . " WHERE parent_id = '0'" . " AND admin_id = '1'";
	    M()->query($sql);
	}

	/**
	 * 保存某商品的关联文章
	 * @param   int     $goods_id
	 * @return  void
	 */
	public static function handle_goods_article($goods_id){
	    $sql = "UPDATE " . 'ybr_goods_article' . " SET " . " goods_id = '$goods_id' " . " WHERE goods_id = '0'" . " AND admin_id = '1'";
	    M()->query($sql);
	}
	

	/**
	 * 检查单个商品是否存在规格
	 *
	 * @param   int        $goods_id          商品id
	 * @return  bool                          true，存在；false，不存在
	 */
	public static function check_goods_specifications_exist($goods_id){
	    $goods_id 	= 	intval($goods_id);
	    $sql 		= 	"SELECT COUNT(a.attr_id) FROM " . 'ybr_attribute' . " AS a, " . 'ybr_goods'. " AS g WHERE a.cat_id = g.goods_type AND g.goods_id = '$goods_id'";
		$count 		= 	M()->query($sql);	
	    if ($count > 0){
	        return true;    //存在
	    }
	    else{
	        return false;    //不存在
	    }
	}
	
	/**
	 * 商品图片相册的处理
	 * 
	 */
	public static function hangdle_goods_gallery($img_array,$goods_id){
		// 找出原来有的相册图片
		$datas			=	M('GoodsGallery')->field("img_id,img_desc")->where("goods_id = '{$goods_id}'")->select();
		$old_img_array	=	array();
		foreach($datas as $img){
			$old_img_array[$img['img_id']] = $img['img_desc']; 
		}
		$old_img_array[72]	=	"132456";
		$old_img_array[73]	=	"78798s79fasf";
		$old_img_array[74]	=	"64s646fasf";
		// 更新原有图片描述
		$repeat_img_id_array	=	array_intersect_key($img_array,$old_img_array); // 取$img_arrray的值覆盖$old_img_array的值
		foreach($repeat_img_id_array as $k => $v){
			$img_id		=	$k;
			//$sql		=	"update ybr_goods_gallery set img_desc = '{$v}' where img_id = '{$img_id}' and goods_id = '{$goods_id}'";
			$sql		=	"update ybr_goods_gallery set img_desc = '{$v}', type_name='{$v}' where img_id = '{$img_id}' and goods_id = '{$goods_id}'";
			M()->query($sql);
		}
		// 插入新的图片: 把图片的id与商品id关联起来
		$unrepeat_img_id_array	=	array_diff_key($img_array,$old_img_array);
		foreach($unrepeat_img_id_array as $k =>$v){
			$img_id		=	$k;
			//$sql		=	" update ybr_goods_gallery set img_desc = '{$v}', goods_id = '{$goods_id}' where img_id = '{$img_id}' ";
			$sql		=	" update ybr_goods_gallery set img_desc = '{$v}', type_name='{$v}', goods_id = '{$goods_id}' where img_id = '{$img_id}' ";
			M()->query($sql);
		}
	}
	
	
	
	
	
	
	
	
			
}




